#include "Demo.h"
#include "Script.h"
#include "QuakeServer.h"

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[])
{
	if (argc < 3)
	{
		cout << "Remaic Studio 2.0.1 by Roman Priborkin" << endl << endl;
		cout << "Usage:" << endl;
		cout << "remstud2.exe indemo.dem script.rs2 [outdemo.dem] [noedit]" << endl;
		return 1;
	}


	cout << "Loading demo..." << endl;
	Demo D;
	if (!D.Load(argv[1]))
	{
		cout << "Failed to load " << argv[1] << endl;
		return 1;
	}
	cout << "Demo loaded" << endl;

	
	cout << "Loading script..." << endl;
	Script S;
	if (!S.Load(argv[2]))
	{
		cout << "Couldn't load " << argv[2] << ", creating a new script" << endl;
		S.CreateDefault(D);
	}
	else
		cout << "Script loaded" << endl;
	
	
	if (argc < 5 || string("noedit") != argv[4])
	{
		cout << "Awaiting client" << endl;
		QuakeServer Server(D,S);
		if (!Server.AcceptClient())
		{
			cout << "Failed to accept client connection" << endl;
			return 1;
		}

		cout << "Client connected, start editing" << endl;
		Server.RunEditing();

		cout << "Client disconnected" << endl;
		
		if (!S.Save(argv[2]))
		{
			cout << "Failed to save load " << argv[2] << ", will try to save to back.rs2" << endl;
			S.Save("back.rs2");
		}
		else
			cout << "Script saved" << endl;
	  
	}
	if (argv[3])
	{
		Demo Out;
		if (!D.Recam(S,Out))
		{
			cout << "Failed to process " << endl;
			return 1;
		}
		else
			cout << "Generated output" << endl;
		
			
		if (!Out.Save(argv[3]))
		{
			cout << "Failed to write " << argv[3] << endl;
			return 1;
		}
		else
			cout << "Saved output" << endl;

	}

	
	return 0;
}
